<?php

namespace Our;

class Common {

    /**
     * 获取http状态码
     * 
     * @param int $num 
     * @return string
     */
    public static function getHttpStatusCode($num) {
        $httpStatusCodes = array(
            100 => "HTTP/1.1 100 Continue",
            101 => "HTTP/1.1 101 Switching Protocols",
            200 => "HTTP/1.1 200 OK",
            201 => "HTTP/1.1 201 Created",
            202 => "HTTP/1.1 202 Accepted",
            203 => "HTTP/1.1 203 Non-Authoritative Information",
            204 => "HTTP/1.1 204 No Content",
            205 => "HTTP/1.1 205 Reset Content",
            206 => "HTTP/1.1 206 Partial Content",
            300 => "HTTP/1.1 300 Multiple Choices",
            301 => "HTTP/1.1 301 Moved Permanently",
            302 => "HTTP/1.1 302 Found",
            303 => "HTTP/1.1 303 See Other",
            304 => "HTTP/1.1 304 Not Modified",
            305 => "HTTP/1.1 305 Use Proxy",
            307 => "HTTP/1.1 307 Temporary Redirect",
            400 => "HTTP/1.1 400 Bad Request",
            401 => "HTTP/1.1 401 Unauthorized",
            402 => "HTTP/1.1 402 Payment Required",
            403 => "HTTP/1.1 403 Forbidden",
            404 => "HTTP/1.1 404 Not Found",
            405 => "HTTP/1.1 405 Method Not Allowed",
            406 => "HTTP/1.1 406 Not Acceptable",
            407 => "HTTP/1.1 407 Proxy Authentication Required",
            408 => "HTTP/1.1 408 Request Time-out",
            409 => "HTTP/1.1 409 Conflict",
            410 => "HTTP/1.1 410 Gone",
            411 => "HTTP/1.1 411 Length Required",
            412 => "HTTP/1.1 412 Precondition Failed",
            413 => "HTTP/1.1 413 Request Entity Too Large",
            414 => "HTTP/1.1 414 Request-URI Too Large",
            415 => "HTTP/1.1 415 Unsupported Media Type",
            416 => "HTTP/1.1 416 Requested range not satisfiable",
            417 => "HTTP/1.1 417 Expectation Failed",
            500 => "HTTP/1.1 500 Internal Server Error",
            501 => "HTTP/1.1 501 Not Implemented",
            502 => "HTTP/1.1 502 Bad Gateway",
            503 => "HTTP/1.1 503 Service Unavailable",
            504 => "HTTP/1.1 504 Gateway Time-out"
        );

        return isset($httpStatusCodes[$num]) ? $httpStatusCodes[$num] : '';
    }

    /**
     * 获取客户端IP
     *
     * @param  boolean $checkProxy
     * @return string
     */
    public static function getClientIp($checkProxy = true) {
        if ($checkProxy && isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP'] != null) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else if ($checkProxy && isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] != null) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        return $ip;
    }

    /**
     * 获取当前访问的url地址
     * 
     * @return string
     */
    public static function getRequestUrl() {
        return 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    }

    /**
     * 加解密
     * @param type $string
     * @param type $operation
     * @param type $key
     * @param type $expiry
     * @return string
     */
    public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
        $ckey_length = 4;
        $key         = md5($key ? $key : $GLOBALS['discuz_auth_key']);

        $keya          = md5(substr($key, 0, 16));
        $keyb          = md5(substr($key, 16, 16));
        $keyc          = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
        $cryptkey      = $keya . md5($keya . $keyc);
        $key_length    = strlen($cryptkey);
        $string        = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);
        $result        = '';
        $box           = range(0, 255);
        $rndkey        = array();
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
        for ($j = $i = 0; $i < 256; $i++) {
            $j       = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp     = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a       = ($a + 1) % 256;
            $j       = ($j + $box[$a]) % 256;
            $tmp     = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if ($operation == 'DECODE') {
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            return $keyc . str_replace('=', '', base64_encode($result));
        }
    }

    /**
     * 获取语言
     * 
     * @return string
     */
    public static function getLang() {
        //http header
        if (!empty($_SERVER["HTTP_LANG"])) {
            switch ($_SERVER["HTTP_LANG"]) {
                case 'zh-tw':
                    return 'Ch';
                    break;
                case 'en':
                    return 'En';
                    break;
                default :
                    return 'Cn';
            }
        }

        //app
        if (!empty($_REQUEST["lang"])) {
            switch ($_REQUEST["lang"]) {
                case 'zh-tw':
                    return 'Ch';
                    break;
                case 'en':
                    return 'En';
                    break;
                default :
                    return 'Cn';
            }
        }

        //browser
        if (!empty($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {
            if (0 === stripos($_SERVER["HTTP_ACCEPT_LANGUAGE"], 'zh-tw')) {
                return 'Ch';
            }
            if (0 === stripos($_SERVER["HTTP_ACCEPT_LANGUAGE"], 'zh-hk')) {
                return 'Ch';
            }
            if (0 === stripos($_SERVER["HTTP_ACCEPT_LANGUAGE"], 'zh-sg')) {
                return 'Ch';
            }
            if (0 === stripos($_SERVER["HTTP_ACCEPT_LANGUAGE"], 'en')) {
                return 'En';
            }
            return 'Cn';
        } else {
            return 'Cn';
        }
    }

    /**
     * 返回数组中指定的一列
     * 
     * @param array $input
     * @param string $columnKey
     * @param string $indexKey
     * @return array
     */
    public static function array_column($input, $columnKey, $indexKey = NULL) {
        if (empty($input)) {
            return array();
        }
        if (is_null($columnKey)) {
            return $input;
        }
        if (function_exists('array_column')) {
            return array_column($input, $columnKey, $indexKey);  //php5.5
        }
        $result = array();
        foreach ($input as $key => $value) {
            if (empty($indexKey)) {
                $result[] = $value[$columnKey];
            } else {
                $result[$value[$indexKey]] = $value[$columnKey];
            }
        }

        return $result;
    }

    /**
     * 用指定的列替换数组的主键
     * 
     * @param array $input
     * @param string $indexKey
     * @return array
     */
    public static function array_key_change($input, $indexKey) {
        if (empty($input)) {
            return array();
        }
        if (empty($indexKey)) {
            return $input;
        }
        $result = array();
        foreach ($input as $value) {
            if (!empty($indexKey)) {
                $result[$value[$indexKey]] = $value;
            }
        }
        return $result;
    }

    /**
     * 获取HTTP自定义头部信息
     * 
     * @param type $key
     * @return type
     */
    public static function getOurHttpByKey($key = 'CID') {
        $httpKey = 'HTTP_' . $key;
        return empty($_SERVER[$httpKey]) ? '' : $_SERVER[$httpKey];
    }

    /**
     * 发起http请求
     * 
     * @param string $url
     * @return string
     */
    public static function httpGet($url) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10); //3秒超时
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
        //检测是否是https访问
        if (strpos($url, 'https') === 0) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }
}
